package com.ly.test.handle.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ly.common.core.bean.dto.MsgDTO;
import com.ly.common.core.constant.BaseConstant;
import com.ly.common.core.enums.MsgTypeEnum;
import com.ly.common.core.enums.MsgUrlEnum;
import com.ly.common.core.exception.ServiceException;
import com.ly.common.core.utils.BaseUtils;
import com.ly.system.mapper.SysMessageMapper;
import com.ly.system.mapper.SysMessageSendMapper;
import com.ly.system.service.ISysMessageTemplateService;
import com.ly.system.service.ISysUserService;
import com.ly.system.system.bean.entity.SysMessage;
import com.ly.system.system.bean.entity.SysMessageSend;
import com.ly.system.system.bean.entity.SysMessageTemplate;
import com.ly.system.system.bean.entity.SysUser;
import com.ly.system.util.HTMLUtils;
import com.ly.test.handle.IMsgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 系统消息
 *
 * @author luoyun
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SystemMsgService implements IMsgService {

    private final ISysMessageTemplateService sysMessageTemplateService;

    private final SysMessageMapper sysMessageMapper;
    private final ISysUserService sysUserService;
    private final SysMessageSendMapper sysMessageSendMapper;

    @Override
    public Boolean supports(String type) {
        return MsgTypeEnum.XT.getType().equals(type);
    }

    /**
     * 仅发送系统消息
     *
     * @param dto
     */
    @Override
    public void sendMessage(MsgDTO dto) {
        log.info("发系统消息");
        SysMessage entity = BeanUtil.copyProperties(dto, SysMessage.class);
        String busType = dto.getBusType();
        Map<String, Object> params = dto.getParams();
        if (StrUtil.isNotEmpty(busType)) {
            // 路由配置
            MsgUrlEnum urlEnum = MsgUrlEnum.getByType(busType);
            entity.setOpenType(urlEnum.getOpenType());
            entity.setOpenPage(urlEnum.getOpenPage());
        }
        String templateCode = dto.getTemplateCode();
        if (StrUtil.isNotEmpty(templateCode)) {
            // 通过模版读取配置
            SysMessageTemplate template = sysMessageTemplateService.getTemplateByCode(templateCode);
            if (template == null) {
                throw new ServiceException("消息模板不存在，模板编码：" + templateCode);
            }
            //如果是markdown类型需要解释
            if(BaseConstant.MSG_TEMPLATE_TYPE_MD.equals(template.getTemplateType())){
                String content = template.getTemplateContent();
                if (StrUtil.isNotEmpty(content) && null != dto.getParams()) {
                    content = HTMLUtils.parseTemplateContent(content, dto.getParams(), true);
                }
                dto.setIsMarkdown(true);
                dto.setMsgContent(HTMLUtils.parseMarkdown(content));
            }else{
                // 模板标题
                final String[] title = {template.getTemplateName() != null ? template.getTemplateName() : dto.getTitle()};
                // 模板内容
                final String[] content = {template.getTemplateContent()};
                String url = null;
                if (params != null) {
                    params.forEach((k, v) -> {
                        String str = "${" + k + "}";
                        String val = String.valueOf(v);
                        title[0] = title[0].replace(str, val);
                        content[0] = content[0].replace(str, val);
                        log.info("当前数据为：{}，内容为：{}", entity.getTitle(), entity.getMsgContent());
                    });
                    Object urlObj = params.get(BaseConstant.MSG_HREF_URL);
                    if (urlObj != null) {
                        url = String.valueOf(params.get(BaseConstant.MSG_HREF_URL));
                    }
                }
                entity.setTitle(title[0]);
                entity.setMsgContent(content[0]);
            }
        }
        if (params != null) {
            // 摘要信息
            Object msgAbstract = params.get(BaseConstant.NOTICE_MSG_SUMMARY);
            if (msgAbstract != null) {
                entity.setMsgAbstract(msgAbstract.toString());
            }
        }
        entity.setPriority(BaseConstant.PRIORITY_M);
        entity.setMsgType(BaseConstant.MSG_TYPE_UESR);
        entity.setSendStatus(BaseConstant.HAS_SEND);
        entity.setSendTime(new Date());
        entity.setSender(BaseUtils.getRealname());
        sysMessageMapper.insert(entity);
        // 2.插入用户通告阅读标记表记录
        String userId = dto.getToUser();
        String[] userIds = userId.split(",");
        String messageId = entity.getId();
        for (int i = 0; i < userIds.length; i++) {
            if (StrUtil.isNotEmpty(userIds[i])) {
                SysUser sysUser = sysUserService.getUserByName(userIds[i]);
                if (sysUser == null) {
                    continue;
                }
                SysMessageSend send = new SysMessageSend();
                send.setMessageId(messageId);
                send.setMsgCategory(entity.getMsgCategory());
                send.setUserId(sysUser.getId());
                send.setReadFlag(BaseConstant.MSG_READ_FLAG_0);
                sysMessageSendMapper.insert(send);
            }
        }
    }
}